package com.lh.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lh.entity.table.*;
import com.lh.mapper.*;
import com.lh.service.TicketProblemInfoApprovalService;
import com.lh.utils.Answer;
import com.lh.utils.LogUtil;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static java.lang.System.out;

@Service
public class TicketProblemInfoApprovalServiceImpl implements TicketProblemInfoApprovalService {

    @Resource
    private TicketProblemInfoApprovalMapper ticketProblemInfoApprovalMapper;

    @Resource
    private DepartmentInfoMapper departmentInfoMapper;

    @Resource
    private ProcessNodeMapper processNodeMapper;

    @Resource
    private ReminderInfoMapper reminderInfoMapper;

    @Resource
    private RectificationInfoApprovalMapper rectificationInfoApprovalMapper;

    @Resource
    private DeadlineNodeApprovalMapper deadlineNodeApprovalMapper;

    private LogUtil LOG = new LogUtil(TicketProblemInfoServiceImpl.class);

    @Override
    public Answer<Object> commitApproval(JSONObject reqJson) {
        try {
            // 1. 提取核心参数
            JSONArray data = reqJson.getJSONArray("ticketProblemInfoApproval");
            String department = reqJson.getString("department"); // 外层部门（与节点departmentName一致）
            if (data == null || data.isEmpty()) {
                return Answer.error("提交的节点数据不能为空");
            }
            if (StrUtil.isBlank(department)) {
                return Answer.error("部门标识（department）不能为空");
            }

            // 2. 从第一个节点提取rectificationId（所有节点共享同一个）
            JSONObject firstNodeJson = data.getJSONObject(0);
            Integer rectificationId = firstNodeJson.getInteger("rectificationId");
            if (rectificationId == null) {
                return Answer.error("rectificationId不能为空");
            }

            // 3. 查询关联的整改信息
            RectificationInfoApproval rectificationInfo = rectificationInfoApprovalMapper.selectOne(
                    new LambdaQueryWrapper<RectificationInfoApproval>()
                            .eq(RectificationInfoApproval::getRectificationId, rectificationId)
                            .eq(RectificationInfoApproval::getApprovalState, "0")
            );
            if (rectificationInfo == null) {
                return Answer.error("整改信息不存在或状态异常（rectificationId=" + rectificationId + "）");
            }

            // 4. 判断当前部门的Ticket是否存在（rectificationId + department联合唯一）
            List<TicketProblemInfoApproval> ticketList = ticketProblemInfoApprovalMapper.selectList(
                    new LambdaQueryWrapper<TicketProblemInfoApproval>()
                            .eq(TicketProblemInfoApproval::getRectificationId, rectificationId)
                            .eq(TicketProblemInfoApproval::getProcessHandlerDepartment, department)
                            .orderByDesc(TicketProblemInfoApproval::getId) // 按ID倒序，取最新的一条
                            .last("LIMIT 1") // 只查一条（MySQL语法，其他数据库用ROWNUM等）
            );
            // 处理查询结果
            TicketProblemInfoApproval existingTicket = null;
            if (ticketList != null && !ticketList.isEmpty()) {
                existingTicket = ticketList.get(0); // 取第一条（最新的）
            }

            Integer ticketId = null;
            TicketProblemInfoApproval ticket = new TicketProblemInfoApproval();

            // 5. 处理Ticket主数据（一次判断，统一处理）
            if (existingTicket != null) {
                // 存在：更新Ticket，删除旧节点
                ticket.setId(existingTicket.getId());
                ticket.setProminentIssue(rectificationInfo.getProjectType());
                ticket.setContent(rectificationInfo.getContent());
                ticket.setSummaryId(1);
                ticket.setTask2Id(rectificationInfo.getTask2Id());
                ticket.setLeadUnit(rectificationInfo.getLeadLeader());
                ticket.setProcessHandlerDepartment(department); // 固定当前部门
                ticket.setStatus("0");
                ticket.setRectificationId(rectificationId);
                ticket.setCompleteDeadline(rectificationInfo.getDeadline());
                ticket.setMainId(rectificationInfo.getTask2Id());
                ticketProblemInfoApprovalMapper.updateById(ticket);
                ticketId = existingTicket.getId();

                // 删除该Ticket关联的所有旧节点
                deadlineNodeApprovalMapper.delete(
                        new LambdaQueryWrapper<DeadlineNodeApproval>()
                                .eq(DeadlineNodeApproval::getDepartmentName, department)
                                .eq(DeadlineNodeApproval::getRectificationId, rectificationId)
                );
            } else {
                // 不存在：新增Ticket
                ticket.setProminentIssue(rectificationInfo.getProjectType());
                ticket.setContent(rectificationInfo.getContent());
                ticket.setSummaryId(1);
                ticket.setTask2Id(rectificationInfo.getTask2Id());
                ticket.setLeadUnit(rectificationInfo.getLeadLeader());
                ticket.setProcessHandlerDepartment(department);
                ticket.setStatus("0");
                ticket.setRectificationId(rectificationId);
                ticket.setCompleteDeadline(rectificationInfo.getDeadline());
                ticket.setMainId(rectificationInfo.getTask2Id());
                Answer<Object> addResult = this.addTicketProblemInfo(ticket);
                if (addResult.getCode() != 200) {
                    return Answer.error("新增Ticket失败：" + addResult.getMsg());
                }
                ticketId = (Integer) addResult.getResult();
            }
            // 6. 批量处理节点（循环插入新节点，关联当前Ticket）
            for (int i = 0; i < data.size(); i++) {
                JSONObject nodeJson = data.getJSONObject(i);
                DeadlineNodeApproval deadlineNode = JSONObject.parseObject(nodeJson.toJSONString(), DeadlineNodeApproval.class);

                // 校验节点必要参数
                if (deadlineNode.getDeadline() == null) {
                    return Answer.error("第" + (i + 1) + "个节点：截止时间（deadline）不能为空");
                }
                if (StrUtil.isBlank(deadlineNode.getName())) {
                    return Answer.error("第" + (i + 1) + "个节点：节点名称（name）不能为空");
                }

                // 重置节点关联信息（覆盖旧mainId，关联当前Ticket）
                deadlineNode.setMainId(ticketId);
                deadlineNode.setRectificationId(rectificationId);
                deadlineNode.setDepartmentName(department); // 统一为当前部门
                deadlineNode.setCreateTime(new Date()); // 刷新创建时间
                deadlineNode.setSort(i); // 按提交顺序设置排序
                deadlineNode.setState("1"); // 统一状态为有效
                deadlineNode.setTypeName("下发"); // 固定类型

                // 插入新节点
                deadlineNodeApprovalMapper.insert(deadlineNode);
            }

            return Answer.ok("操作成功：" + (existingTicket != null ? "更新Ticket及节点" : "新增Ticket及节点")
                    + "，共" + data.size() + "个节点");
        } catch (Exception e) {
            e.printStackTrace();
            return Answer.error("操作失败：" + e.getMessage());
        }
    }

//    @Override
//    public Answer<Object> commitApproval(JSONObject reqJson) {
//        try {
//            JSONArray data = reqJson.getJSONArray("ticketProblemInfoApproval");
//            Integer id = null;
//            for (int i = 0; i < data.size(); i++) {
//                JSONObject jsonObject = data.getJSONObject(i);
//                DeadlineNodeApproval deadlineNode = JSONObject.parseObject(jsonObject.toJSONString(), DeadlineNodeApproval.class);
//                Integer mainId = deadlineNode.getMainId();
//                Integer rectificationId = deadlineNode.getRectificationId();
//                Date deadline = deadlineNode.getDeadline();
//                String departmentName = deadlineNode.getDepartmentName();
//                if (mainId == null) {
//                    continue;
//                }
//                if (deadline == null) {
//                    continue;
//                }
//                if (StrUtil.isBlank(departmentName)) {
//                    continue;
//                }
//                RectificationInfoApproval rectificationInfo = rectificationInfoApprovalMapper.selectOne(new LambdaQueryWrapper<RectificationInfoApproval>()
//                        .eq(RectificationInfoApproval::getRectificationId,rectificationId).eq(RectificationInfoApproval::getApprovalState,"0"));
//                if (rectificationInfo == null) {
//                    continue;
//                }
//                if (i == 0) {
//                    TicketProblemInfoApproval ticketProblemInfo = new TicketProblemInfoApproval();
//                    ticketProblemInfo.setProminentIssue(rectificationInfo.getProjectType());
//                    ticketProblemInfo.setContent(rectificationInfo.getContent());
//                    ticketProblemInfo.setSummaryId(1);
//                    ticketProblemInfo.setTask2Id(rectificationInfo.getTask2Id());
//                    ticketProblemInfo.setLeadUnit(rectificationInfo.getLeadLeader());
//                    ticketProblemInfo.setProcessHandlerDepartment(departmentName);
//                    ticketProblemInfo.setStatus("0");
//                    ticketProblemInfo.setRectificationId(rectificationId);
//                    ticketProblemInfo.setCompleteDeadline(rectificationInfo.getDeadline());
//                    ticketProblemInfo.setMainId(rectificationInfo.getTask2Id());
//                    Answer<Object> objectAnswer = this.addTicketProblemInfo(ticketProblemInfo);
//                    if (objectAnswer.getCode() == 200) {
//                        id = (Integer) objectAnswer.getResult();
//                    } else {
//                        return Answer.error(objectAnswer.getMsg());
//                    }
//                }
//                if (id != null) {
//                    deadlineNode.setCreateTime(new Date());
//                    deadlineNode.setSort(i);
//                    deadlineNode.setState("1");
//                    deadlineNode.setRectificationId(rectificationId);
//                    deadlineNode.setMainId(id);
//                    deadlineNode.setTypeName("下发");
//                    deadlineNodeApprovalMapper.insert(deadlineNode);
//                }
//            }
//            return Answer.ok("添加成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Answer.error("添加失败");
//        }
//    }

    @Override
    public Answer<Object> addTicketProblemInfo(TicketProblemInfoApproval ticketProblemInfo) {
        try {
            String processHandlerDepartment = ticketProblemInfo.getProcessHandlerDepartment();
            if (StrUtil.isNotBlank(processHandlerDepartment)) {
                List<DepartmentInfo> departmentInfoList = departmentInfoMapper.selectList(new LambdaQueryWrapper<DepartmentInfo>().eq(DepartmentInfo::getDepartmentName, processHandlerDepartment));
                if (CollectionUtil.isNotEmpty(departmentInfoList)) {
                    String areaName = departmentInfoList.get(0).getAreaName();
                    ticketProblemInfo.setAreaName(areaName);
                }
            }
            Date date = new Date();
            ticketProblemInfo.setCreatedTime(date);
            ticketProblemInfo.setProcessHandlerDepartment(processHandlerDepartment);
            ticketProblemInfo.setContent(ticketProblemInfo.getName());
            ticketProblemInfo.setRectificationId(ticketProblemInfo.getRectificationId());
            ticketProblemInfoApprovalMapper.insert(ticketProblemInfo);
            return Answer.ok(ticketProblemInfo.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return LOG.error(Answer.build(), "请求addTicketProblemInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> updateTicketProblemInfo(TicketProblemInfoApproval ticketProblemInfo) {
        ticketProblemInfoApprovalMapper.updateById(ticketProblemInfo);
        return Answer.ok("修改成功");
    }
    @Override
    public Answer<Object> deleteDepartment(TicketProblemInfoApproval ticketProblemInfo) {
        if (StrUtil.isEmptyIfStr(ticketProblemInfo.getDepartmentName())){
            return Answer.error("没有责任单位,无法删除");
        }
        List<TicketProblemInfoApproval> ticketList = ticketProblemInfoApprovalMapper.selectList(
                new LambdaQueryWrapper<TicketProblemInfoApproval>()
                        .eq(TicketProblemInfoApproval::getRectificationId, ticketProblemInfo.getRectificationId())
                        .eq(TicketProblemInfoApproval::getProcessHandlerDepartment, ticketProblemInfo.getDepartmentName())
        );
        // 2. 批量删除Ticket（关键：先提取id列表）
        if (ticketList != null && !ticketList.isEmpty()) {
            // 从ticketList中提取所有id，组装成List<Integer>
            List<Integer> ticketIds = ticketList.stream()
                    .map(TicketProblemInfoApproval::getId) // 假设Ticket的主键字段是id
                    .collect(Collectors.toList());

            // 执行批量删除
            ticketProblemInfoApprovalMapper.deleteBatchIds(ticketIds);
        }
        deadlineNodeApprovalMapper.delete(
                new LambdaQueryWrapper<DeadlineNodeApproval>()
                        .eq(DeadlineNodeApproval::getDepartmentName, ticketProblemInfo.getDepartmentName())
                        .eq(DeadlineNodeApproval::getRectificationId, ticketProblemInfo.getRectificationId())
        );
        return Answer.ok("删除成功");
    }

}
